package com.dhh.activity;

import java.util.Calendar;
import com.dhh.R;
import com.dhh.dao.DataBaseHelper;
import com.dhh.util.CUtil;
import com.dhh.util.Constant;
import com.dhh.util.manager.FoodLogManager;
import com.dhh.util.manager.FoodManager;
import com.dhh.util.manager.PlanManager;
import com.dhh.vo.Food;
import com.dhh.vo.FoodLog;
import greendroid.app.GDActivity;
import greendroid.widget.NormalActionBarItem;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.InputType;
import android.text.method.DigitsKeyListener;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;

public class FoodAddDetailActivity extends GDActivity implements View.OnClickListener {
	private FoodManager fManager;
	private FoodLogManager flManager;
	private PlanManager pManager;
	private Food food;
	private DataBaseHelper db;
	private FoodLog log;
	private String fid;
	
	private Button addButton;
	private TextView tFoodName;
	private TextView tFoodGroup;
	private TextView tQuatity;
	private TextView tEnergy;
	private TextView tProtein;
	private TextView tFat;
	private TextView tCarb;
	private TextView tPeriod;
	private LinearLayout quatityLst;
	private LinearLayout periodLayout;
	
	@Override
    public void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setActionBarContentView(R.layout.add_food);
		
        fid = getIntent().getExtras().getString("foodId");        
        initActionBar();
        intitView();       
	}
	
	@Override
	public void onStart() {
        super.onStart();   
        db = new DataBaseHelper(getBaseContext());
        db.openDataBase();
        
        fManager = new FoodManager(db);
        flManager = new FoodLogManager(db);
        pManager = new PlanManager(db);
        
        log = new FoodLog();
        log.setQuatity("100");
        log.setPlanEnergy(pManager.getCurrentPlan().getEnergy());
        log.setPeriod("Breakfast");
        food = fManager.getFood(fid);
		initLog(food);
        fillData(); 
	}
	
	private void initActionBar(){
		getActionBar().setTitle("Add Food");
        getActionBar().setBackgroundColor(Color.rgb(82, 135, 241));
        getActionBar().getChildAt(0).
    	setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(FoodAddDetailActivity.this,HomeActivity.class);	
				startActivity(intent);
			}}); 
	}
	
	private void intitView(){
		addButton =(Button) this.findViewById(R.id.adf_add_button);
		addButton.setOnClickListener(this);
		tFoodName = (TextView) this.findViewById(R.id.adf_food_name);
		tFoodGroup = (TextView) this.findViewById(R.id.adf_food_group);
		tQuatity = (TextView) this.findViewById(R.id.adf_quitity);
		tEnergy = (TextView) this.findViewById(R.id.adf_energy);
		tProtein = (TextView) this.findViewById(R.id.adf_protein);
		tFat = (TextView) this.findViewById(R.id.adf_fat);
		tCarb = (TextView) this.findViewById(R.id.adf_carb);
		tPeriod = (TextView) this.findViewById(R.id.adf_period);
		
		quatityLst = (LinearLayout) this.findViewById(R.id.adf_quatity_lst);
		quatityLst.setOnClickListener(this);
		
		periodLayout = (LinearLayout) this.findViewById(R.id.adf_period_lst);
		periodLayout.setOnClickListener(this);
	}
	
	private void fillData(){	
		initLog(food);
		tFoodName.setText(food.getFoodName());
		tFoodGroup.setText(food.getFoodGroup());
		tEnergy.setText(log.getEnergy());
		tProtein.setText(CUtil.formatNum(Double.valueOf(food.getProtein())*Double.valueOf(log.getQuatity())/100)+"g");
		tFat.setText(CUtil.formatNum(Double.valueOf(food.getFat())*Double.valueOf(log.getQuatity())/100)+"g");
		tCarb.setText(CUtil.formatNum(Double.valueOf(food.getCarb())*Double.valueOf(log.getQuatity())/100)+"g"); 
		tQuatity.setText(log.getQuatity()+"g");
		tPeriod.setText(log.getPeriod());
	}
	
	private void initLog(Food food){
		log.setFoodName(food.getFoodName());
		log.setFoodGroup(food.getFoodGroup());
		log.setEnergy(String.valueOf(Math.round(Double.valueOf(food.getEnergy())*(Double.valueOf(log.getQuatity())/100))));
		log.setDate(CUtil.getDate(Calendar.getInstance().getTime()));			
	}
	
	@Override
	public void onClick(View v) {
		if(R.id.adf_quatity_lst == v.getId()){		
			getAlertDialogTextEdit("Please input:",log.getQuatity(),v.getId()).show();
		}else if(R.id.adf_period_lst == v.getId()){
			this.getAlertDialogChoice("Please input:", null, new String[]{"Breakfast","Lunch","Dinner","Snack"}).show();
		}else if(R.id.adf_add_button == v.getId()){
			flManager.addFoodLog(log);
			Intent intent = new Intent(FoodAddDetailActivity.this,FoodAddActivity.class);
			intent.putExtra(Constant.FROM_ACTIVITY, Constant.FA_FOOD_LOG);
			startActivity(intent);
		}
	}
	
	@Override
	protected void onStop(){
		super.onStop();
		if (db != null) {
			db.close();
		}
	}
	
	AlertDialog getAlertDialogTextEdit(String title,String defaultValue,final int id){
		final FrameLayout fl = new FrameLayout(FoodAddDetailActivity.this);
		final EditText input = new EditText(FoodAddDetailActivity.this);
		input.setGravity(Gravity.CENTER);
		fl.addView(input, new FrameLayout.LayoutParams(FrameLayout.LayoutParams.FILL_PARENT, FrameLayout.LayoutParams.WRAP_CONTENT));
		input.setText(defaultValue);
		DigitsKeyListener digkl = DigitsKeyListener.getInstance(true,true);
		input.setKeyListener(digkl);
		input.setInputType(InputType.TYPE_CLASS_NUMBER);
		
		AlertDialog.Builder builder = new AlertDialog.Builder(FoodAddDetailActivity.this);
		builder.setView(fl).setTitle(title).
			setPositiveButton("OK", new DialogInterface.OnClickListener(){		    	 
                @Override
                public void onClick(DialogInterface d, int which) {
                	if(R.id.adf_quatity_lst == id){
                    	log.setQuatity(input.getText().toString());
                	}
        			fillData();
                	d.dismiss();
                }
		    }).
		    setNegativeButton("Cancel", new DialogInterface.OnClickListener(){		    	 
                @Override
                public void onClick(DialogInterface d, int which) {
                	d.dismiss();
                }
		    });
		
		return builder.create();
	}
	
	int selectedItem = 0;
	AlertDialog getAlertDialogChoice(String title,String value,final String items[]){
		AlertDialog.Builder ab = new AlertDialog.Builder(FoodAddDetailActivity.this);
		ab.setTitle(title);		
		ab.setSingleChoiceItems(items, selectedItem,
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int whichButton) {
						selectedItem = whichButton;
					}
				})
				.setPositiveButton("OK", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int whichButton) {
						log.setPeriod(items[selectedItem]);				
						fillData();
					}
				})
				.setNegativeButton("Cancel",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,int whichButton) {
								dialog.dismiss();
							}
						});
		return ab.create();
	}
}
